const express = require("express");
const http = require("http");
const { Server } = require("socket.io");

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

const rooms = {}; // 存储房间用户信息

io.on("connection", (socket) => {
    console.log("User connected:", socket.id);

    socket.on("join-room", (roomId) => {
        if (!rooms[roomId]) rooms[roomId] = [];
        rooms[roomId].push(socket.id);
        socket.join(roomId);
        console.log(`User ${socket.id} joined room ${roomId}`);

        socket.emit("room-users", rooms[roomId]);
        socket.to(roomId).emit("new-user", socket.id);
    });

    socket.on("offer", ({ roomId, offer, from }) => {
        socket.to(roomId).emit("offer", { from, offer });
    });

    socket.on("answer", ({ roomId, answer, from }) => {
        socket.to(roomId).emit("answer", { from, answer });
    });

    socket.on("candidate", ({ roomId, candidate, from }) => {
        socket.to(roomId).emit("candidate", { from, candidate });
    });

    socket.on("chat-message", ({ roomId, message, from }) => {
        socket.to(roomId).emit("chat-message", { message, from });
    });

    socket.on("disconnect", () => {
        for (const roomId in rooms) {
            rooms[roomId] = rooms[roomId].filter(id => id !== socket.id);
            socket.to(roomId).emit("user-disconnected", socket.id);
        }
        console.log(`User disconnected: ${socket.id}`);
    });
});

server.listen(3000, () => console.log("Server running on http://localhost:3000"));
